#include "hbreceiverthread.h"

#include <QUdpSocket>
#include <QDataStream>
#include <QDateTime>
#include <QTimer>
#include <QtTest/QtTest>
#include <string>
HBReceiverThread::HBReceiverThread( QWidget *parent ) : QLabel( parent )
{
  setText( "Waiting for data." );
  firsthb = true;
  cont = 0;
  timer = new QTimer( this );
  timer->setInterval( 900 );
  socket = new QUdpSocket( this );
  socket->bind( 9988 );

  connect( socket, SIGNAL(readyRead()), this, SLOT(dataPending()) );
  connect( timer, SIGNAL(timeout()), this, SLOT(checadorDeTempo()) );
}

QBool HBReceiverThread::dataPending()
{
  if(firsthb == true){
     firsthb = false;
     timer->start();
  }
  lastUpdate = QTime::currentTime();
  setText("Recebendo");
  QDateTime dt = QDateTime::currentDateTime();
  qDebug("hbrecv received a heartbeat at " + dt.toString().toLatin1(),cont);
  cont++;
  QByteArray buffer( socket->pendingDatagramSize(), 0 );
  socket->readDatagram( buffer.data(), buffer.size() );
  return QBool (true);
}

QString HBReceiverThread::checadorDeTempo(){
    QTime tempoAtual = QTime::currentTime();
       if(lastUpdate.secsTo(tempoAtual)>3){
            timer->stop();
            setText("Nao Recebeu");
            cont = 0;
            firsthb = true;
            qDebug("hbrecv missed heartbeat");
            return "continua"; //ele continua ate 3 segundos.. apos isso se nao tiver recenbo mais passad pro else abaixo
       }
       else qDebug("waitingg for hearbeat...");


           return "parou";
}

void HBReceiverThread::dataPendingTest(){
    QBool recebeTest = dataPending();
    QCOMPARE(recebeTest, QBool(true));
}

void HBReceiverThread::checadorDeTempoTest(){
    QString str = checadorDeTempo();
    if (str.compare("parou")){
        qDebug("Houve interrupcao do recebimento de heartbeats!");
        QCOMPARE(str.toUpper(), QString("CONTINUA"));
    }else
        QCOMPARE(str.toUpper(), QString("PAROU"));
}
